/**
 * 表格组件 Store
 * 管理表格的排序、过滤和分页状态
 */
import { observable, action } from '../../../../../miniprogram_npm/mobx-miniprogram/index';

export const tableStore = observable({
  // 排序状态
  sorting: {
    field: '', // 当前排序字段
    order: 'asc' // 升序/降序
  },
  
  // 过滤状态
  filterState: {
    field: '',
    value: null
  },
  
  // 分页信息
  pageInfo: {
    current: 1,
    pageSize: 10,
    total: 0,
    totalPages: 0
  },
  
  // 设置排序状态
  setSorting: action(function(sort) {
    if (!sort || !sort.field) return;
    
    this.sorting = {
      field: sort.field,
      order: sort.order || 'asc'
    };
  }),
  
  // 设置过滤状态
  setFilterState: action(function(filter) {
    if (!filter || !filter.field) return;
    
    this.filterState = {
      field: filter.field,
      value: filter.value
    };
    
    // 重置到第一页
    this.pageInfo.current = 1;
  }),
  
  // 重置过滤
  resetFilter: action(function() {
    this.filterState = {
      field: '',
      value: null
    };
  }),
  
  // 重置排序
  resetSorting: action(function() {
    this.sorting = {
      field: '',
      order: 'asc'
    };
  }),
  
  // 初始化分页信息
  resetPage: action(function(params) {
    const { total, pageSize } = params || {};
    
    this.pageInfo = {
      current: 1,
      pageSize: pageSize || 10,
      total: total || 0,
      totalPages: Math.ceil((total || 0) / (pageSize || 10))
    };
  }),
  
  // 下一页
  nextPage: action(function() {
    if (this.pageInfo.current < this.pageInfo.totalPages) {
      this.pageInfo.current += 1;
    }
  }),
  
  // 上一页
  prevPage: action(function() {
    if (this.pageInfo.current > 1) {
      this.pageInfo.current -= 1;
    }
  }),
  
  // 跳转到指定页
  goToPage: action(function(page) {
    if (page >= 1 && page <= this.pageInfo.totalPages) {
      this.pageInfo.current = page;
    }
  }),
  
  // 更新总数
  updateTotal: action(function(total) {
    this.pageInfo.total = total;
    this.pageInfo.totalPages = Math.ceil(total / this.pageInfo.pageSize);
    
    // 确保当前页在有效范围内
    if (this.pageInfo.current > this.pageInfo.totalPages) {
      this.pageInfo.current = Math.max(1, this.pageInfo.totalPages);
    }
  })
}); 